package com.cloud.rou.im.connection.container.session;

import com.cloud.rou.im.connection.container.connection.Connection;
import com.cloud.rou.im.connection.container.event.SessionEvent;
import com.cloud.rou.im.connection.container.listen.SessionListener;
import com.cloud.rou.im.connection.container.manager.SessionManager;
import com.cloud.rou.im.connection.container.manager.SessionManagerHolder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 */
@Data
@AllArgsConstructor
@Builder
public class Session {

    private Long userId;

    private Connection connection;

    private List<SessionListener> listeners=new ArrayList<>();

    public void addListener(SessionListener listener){
        listeners.add(listener);
    }

    public void created(){
        listeners.forEach(listener -> listener.sessionCreated(SessionEvent
                .builder().session(this).build()));

    }
    public void destroyed(){
        listeners.forEach(listener -> listener.sessionDestroyed(SessionEvent
                .builder().session(this).build()));
    }

    public static void destroyedByUserId(Long userId){
        SessionManager manager = SessionManagerHolder.getManager();
        Session session = manager.getConnectSessionByUserId(userId);
        session.destroyed();
    }
}
